package com.zhenwgang.listen_books.servlet.album;

import com.zhenwgang.listen_books.repository.TrackRepo;
import com.zhenwgang.listen_books.view_object.ResultView;
import com.zhenwgang.listen_books.view_object.UserVO;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Violet
 * @date 2022/07/21 20:31
 **/
@WebServlet("/studio/album/candidate.json")
public class CandidateJsonServlet extends HttpServlet {
    private TrackRepo trackRepo = new TrackRepo();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int aid = Integer.parseInt(req.getParameter("aid"));

        HttpSession session = req.getSession(false);
        if (session == null) {
            throw new RuntimeException("未登录");
        }

        UserVO currentUser = (UserVO) session.getAttribute("currentUser");
        if (currentUser == null) {
            throw new RuntimeException("未登录");
        }

        ResultView resultView = new ResultView();
        resultView.username = currentUser.username;
        resultView.aid = aid;

        trackRepo.selectListByUidAndTidNotIn(currentUser.uid, aid, resultView);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(resultView);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}